import 'package:flutter/material.dart';

// ignore: must_be_immutable
class SelfUpAndDown extends StatefulWidget {
  SelfUpAndDown({
    @required this.hasPage,
    @required this.startDownFresh,
    @required this.startUpFresh,
    @required this.buildItem,
    @required this.listData,
    @required this.sController,
    this.noLoadingText = '上拉加载更多',
    this.noDataText = '已无更多数据',
    this.loadingWidget
  });

  bool isLoading = false;
  bool isUpLoading = false;
  bool hasPage = true;
  List listData = [];
  final String noLoadingText;
  final String noDataText;
  final Widget loadingWidget;
  ScrollController sController;
  final Function startDownFresh;
  final Function startUpFresh;
  final Function buildItem;



  @override
  _SelfUpAndDownState createState() => _SelfUpAndDownState();
}

class _SelfUpAndDownState extends State<SelfUpAndDown> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.sController.addListener(() async{
      if ( widget.sController.position.pixels ==
          widget.sController.position.maxScrollExtent) {
        if(widget.isUpLoading){
          return null;
        }
        //数据没有了 直接返回
        if(!widget.hasPage){
          setState(() {
            widget.isUpLoading = false;
          });
          return;
        }
        //开始上拉
        setState(() {
          widget.isUpLoading = true;
        });
        //如果有数据 执行下拉
        if(widget.hasPage){
          await widget.startUpFresh();
          //结束
          setState(() {
            widget.isUpLoading = false;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    //注销
    print('注销');
    widget.sController.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      child: ListView.builder(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.all(8),
          itemCount:( widget.listData.length + 1),
          controller:widget.sController ,
          itemBuilder: (BuildContext context, int index) {
            //如果没有下一页显示没有更多数据！
            if(!widget.hasPage){
              if(index == widget.listData.length){
                return _loadingWidget(Center(child: Text(widget.noDataText)));
              }
              return _buildMessageCom(index);

            }else{
              //如果 正在更新 显示正在加载
              if(widget.isUpLoading && index == widget.listData.length){
                return _loadingWidget(widget.loadingWidget != null?widget.loadingWidget:Image.network('http://hbimg.b0.upaiyun.com/5ac0d375bfb83e892b4884bb1d7e5046d223da2d2bd08-LrjhBO_fw658',fit: BoxFit.cover,height: 30));
              }else{
                if(index == widget.listData.length){
                  return _loadingWidget(Center(child: Text(widget.noLoadingText)));
                }
                return _buildMessageCom(index);
              }
            }

          }
      ),
      onRefresh: _onFresh,
    );
  }
  Widget _loadingWidget(wg){

    return new Padding(
        padding: EdgeInsets.fromLTRB(0.0, 14.0, 0.0, 14.0),
        child: new Opacity(
            opacity: 1,
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: wg,
                )
              ],
            )));
  }
  Future _onFresh() async{
    if(widget.isLoading){
      return;
    }
    //开始下拉
    setState(() {
      widget.isLoading = true;
    });
    //下拉动作 这里会返回一个类似promise的东西 就会跳过后边的（也就是跳出当前函数） 执行其他内容，当 promise里边的执行完毕了，就会执行后边的
    await widget.startDownFresh();
    //关闭下拉
    setState(() {
      widget.isLoading = false;
    });
  }
  //构建 列表
  Widget _buildMessageCom(index){
    return widget.buildItem(index);
  }

}

